package me.sdevil507.activemq.delay;

import lombok.extern.slf4j.Slf4j;
import org.apache.activemq.ScheduledMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.jms.core.JmsMessagingTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.jms.*;

/**
 * 延迟消息队列消息生产者
 *
 * @author sdevil507
 */
@Component
@Slf4j
public class DelayProducer {

    @Autowired
    @Qualifier("delayQueue")
    private Queue delayQueue;

    @Resource
    private JmsMessagingTemplate jmsMessagingTemplate;

    /**
     * 延迟消息发送
     *
     * @param msg  消息主体
     * @param time 延迟时间(单位:ms)
     */
    public void sendDelayMessage(String msg, Long time) {
        //获取连接工厂
        ConnectionFactory connectionFactory = this.jmsMessagingTemplate.getConnectionFactory();
        try {
            //获取连接
            Connection connection = connectionFactory.createConnection();
            connection.start();
            //获取session
            Session session = connection.createSession(Boolean.TRUE, Session.AUTO_ACKNOWLEDGE);
            MessageProducer producer = session.createProducer(delayQueue);
            producer.setDeliveryMode(DeliveryMode.PERSISTENT);
            TextMessage message = session.createTextMessage(msg);
            //设置延迟时间
            message.setLongProperty(ScheduledMessage.AMQ_SCHEDULED_DELAY, time);
            //发送
            producer.send(message);
            session.commit();
            producer.close();
            session.close();
            connection.close();
        } catch (JMSException e) {
            e.printStackTrace();
        }
    }
}
